<template>
  <div class="admin-dashboard">
    <!-- 顶部导航 -->
    <header class="dashboard-header">
      <h1>客服管理系统</h1>
      <div class="user-info">
        <span>{{ adminName }} ({{ getStatusText(adminStatus) }})</span>
        <button @click="logout" class="logout-btn">
          <i class="fa fa-sign-out"></i>
        </button>
      </div>
    </header>

    <div class="dashboard-content">
      <!-- 左侧会话列表 -->
      <div class="session-list">
        <div class="search-box">
          <input
              type="text"
              placeholder="搜索会话..."
              v-model="searchKeyword"
          >
          <i class="fa fa-search"></i>
        </div>

        <div class="session-items">
          <div
              v-for="session in filteredSessions"
              :key="session.id"
              :class="['session-item',
              session.id === currentSessionId ? 'active' : '',
              session.adminId === null && session.unreadCount > 0 ? 'unassigned-unread' : ''
            ]"
              @click="switchSession(session)"
          >
            <div class="session-avatar">
              <img :src="`https://picsum.photos/200/200?random=${session.userId}`" alt="用户头像">
              <span v-if="session.unreadCount > 0" class="unread-badge">{{ session.unreadCount }}</span>
              <!-- 未分配会话标签 -->
              <span v-if="session.adminId === null" class="unassigned-tag">新会话</span>
            </div>

            <div class="session-info">
              <div class="session-header">
                <h4>{{ session.user.nickname || '访客用户' }}</h4>
                <span class="session-time">{{ formatTime(session.lastMessageTime) }}</span>
              </div>

              <p class="last-message">{{ session.lastMessage || '新会话' }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧聊天区域 -->
      <div class="chat-area" v-if="currentSessionId">
        <!-- 聊天头部 -->
        <div class="chat-header">
          <div class="user-info">
            <img :src="`https://picsum.photos/200/200?random=${currentSession.userId}`" alt="用户头像">
            <div>
              <h3>{{ currentSession.user.nickname || '访客用户' }}</h3>
              <p v-if="currentSession.userPhone" class="user-phone">{{ currentSession.userPhone }}</p>
              <p v-else class="user-anonymous">匿名用户</p>
            </div>
          </div>

          <div class="chat-tools">
            <button class="tool-btn" @click="changeStatus(1)" :class="{active: adminStatus === 1}">
              <i class="fa fa-check"></i> 在线
            </button>
            <button class="tool-btn" @click="changeStatus(2)" :class="{active: adminStatus === 2}">
              <i class="fa fa-clock-o"></i> 忙碌
            </button>
            <button class="tool-btn" @click="endSession">
              <i class="fa fa-times"></i> 结束会话
            </button>
          </div>
        </div>

        <!-- 聊天内容 -->
        <div class="chat-messages" ref="messageContainer">
          <div
              v-for="(msg, index) in messages"
              :key="index"
              :class="['message-item', msg.senderType === 2 ? 'admin-message' : 'user-message']"
          >
            <!-- 客服头像 -->
            <div v-if="msg.senderType === 2" class="avatar">
              <img src="https://picsum.photos/200/200?random=admin" alt="客服头像">
            </div>

            <!-- 消息内容 -->
            <div :class="['message-content', msg.senderType === 2 ? 'admin-content' : 'user-content']">
              <template v-if="msg.messageType === 1">
                {{ msg.content }}
              </template>
              <template v-if="msg.messageType === 2">
                <img :src="msg.content" alt="聊天图片" class="message-image">
              </template>
              <span class="message-time">{{ formatTime(msg.sendTime) }}</span>
            </div>

            <!-- 用户头像 -->
            <div v-if="msg.senderType === 1" class="avatar">
              <img :src="`https://picsum.photos/200/200?random=${currentSession.userId}`" alt="用户头像">
            </div>
          </div>

          <!-- 正在输入提示 -->
          <div v-if="isUserTyping" class="message-item user-message">
            <div class="avatar">
              <img :src="`https://picsum.photos/200/200?random=${currentSession.userId}`" alt="用户头像">
            </div>
            <div class="message-content user-content typing-indicator">
              <span class="dot"></span>
              <span class="dot"></span>
              <span class="dot"></span>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
          <div class="input-tools">
            <input
                type="file"
                ref="imageInput"
                accept="image/*"
                @change="handleImageSelect"
                class="hidden"
            >
            <button @click="selectImage" class="tool-btn">
              <i class="fa fa-picture-o"></i>
            </button>
            <button class="tool-btn">
              <i class="fa fa-smile-o"></i>
            </button>
          </div>

          <div class="input-wrapper">
            <input
                type="text"
                v-model="messageContent"
                placeholder="输入回复..."
                @keydown.enter="sendMessage"
                @input="handleTyping"
            >
            <button @click="sendMessage" class="send-btn">
              发送
            </button>
          </div>
        </div>
      </div>

      <!-- 选择会话提示 -->
      <div class="no-session" v-else>
        <i class="fa fa-comments"></i>
        <p>请选择一个会话开始聊天</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';

const router = useRouter();
const store = useStore();
const adminId = store.state.adminId;
const adminName = ref('在线客服');
const adminStatus = ref(1); // 默认在线状态（1-在线，2-忙碌，0-离线）

// 会话管理
const sessions = ref([]);
const filteredSessions = ref([]);
const currentSession = ref(null);
const currentSessionId = ref('');
const searchKeyword = ref('');

// 聊天状态
const messages = ref([]);
const messageContent = ref('');
const isUserTyping = ref(false);
const messageContainer = ref(null);
const imageInput = ref(null);
const ws = ref(null);
const typingTimer = ref(null);

// 登出
const logout = () => {
  // 登出时更新状态为离线
  updateAdminStatus(0);
  if (ws.value) {
    ws.value.close();
  }
  store.dispatch('logout');
  router.push('/admin/login');
};

// 切换会话
const switchSession = (session) => {
  currentSessionId.value = session.id;
  currentSession.value = session;
  messages.value = []; // 清空当前消息列表
  loadSessionMessages(session.id);

  // 标记已读并绑定会话（如果是未分配的未读会话）
  if (session.unreadCount > 0) {
    markAsRead(session.id);
  }
};

// 加载所有会话（包括未分配的未读会话）
const loadSessions = () => {
  const { $axios } = require('@/main').default.config.globalProperties;
  $axios.get('/admin/sessions', {
    params: { adminId }
  }).then(res => {
    sessions.value = res.data.data || [];
    filterSessions();

    // 如果没有选中会话且有会话列表，默认选中第一个
    if (!currentSessionId.value && sessions.value.length > 0) {
      switchSession(sessions.value[0]);
    }
  }).catch(err => {
    console.error('加载会话列表失败:', err);
  });
};

// 过滤会话
const filterSessions = () => {
  if (!searchKeyword.value) {
    filteredSessions.value = [...sessions.value];
  } else {
    const keyword = searchKeyword.value.toLowerCase();
    filteredSessions.value = sessions.value.filter(session =>
        (session.user.nickname && session.user.nickname.toLowerCase().includes(keyword)) ||
        (session.lastMessage && session.lastMessage.toLowerCase().includes(keyword)) ||
        (session.userPhone && session.userPhone.includes(keyword))
    );
  }
};

// 加载会话消息
const loadSessionMessages = (sessionId) => {
  const { $axios } = require('@/main').default.config.globalProperties;
  $axios.get('/admin/messages', {
    params: { sessionId, adminId }
  }).then(res => {
    console.log("messages.value:",res.data.data)
    messages.value = (res.data.data.messages || []).map(msg => ({
      ...msg,
      senderType: msg.senderType || (msg.senderId === adminId ? 2 : 1),
      messageType: msg.messageType || 1
    }));
    scrollToBottom();
  }).catch(err => {
    console.error('加载会话消息失败:', err);
  });
};

// 标记消息为已读 - 同时完成会话绑定
const markAsRead = (sessionId) => {
  const { $axios } = require('@/main').default.config.globalProperties;
  $axios.post('/admin/read', {
    sessionId,
    adminId
  }).then(() => {
    const session = sessions.value.find(s => s.id === sessionId);
    if (session) {
      session.unreadCount = 0;
      if (session.adminId === null) {
        session.adminId = adminId;
      }
      filterSessions();
    }
  }).catch(err => {
    console.error('标记已读失败:', err);
  });
};

// 结束会话
const endSession = () => {
  if (currentSessionId.value && confirm('确定要结束当前会话吗？')) {
    const {$axios} = require('@/main').default.config.globalProperties;
    $axios.post('/admin/end-session', {
      sessionId: currentSessionId.value,
      adminId
    }).then(() => {
      messages.value = [];
      currentSessionId.value = '';
      currentSession.value = null;
      loadSessions();
    }).catch(err => {
      console.error('结束会话失败:', err);
    });
  }
};

// 更改客服状态
const changeStatus = (status) => {
  if (adminStatus.value !== status) {
    adminStatus.value = status;
    updateAdminStatus(status);
  }
};

// 更新客服状态到后端
const updateAdminStatus = (status) => {
  const {$axios} = require('@/main').default.config.globalProperties;
  $axios.post('/admin/status', {
    adminId,
    status
  }).then(() => {
    console.log(`客服状态已更新为: ${status}`);
  }).catch(err => {
    console.error('更新客服状态失败:', err);
  });
};

// 获取状态文本描述
const getStatusText = (status) => {
  switch (status) {
    case 0:
      return '离线';
    case 1:
      return '在线';
    case 2:
      return '忙碌';
    default:
      return '未知';
  }
};

// 初始化WebSocket
const initWebSocket = () => {
  if (!adminId) return;

  const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  const host = `${window.location.hostname}:9990`;
  const url = `${protocol}//${host}/ws?adminId=${adminId}&role=admin`;

  ws.value = new WebSocket(url);

  ws.value.onopen = () => {
    console.log('客服端WebSocket连接已建立');
    // // 连接建立后更新状态为在线
    // if (adminStatus.value !== 1) {
    //   adminStatus.value = 1;
    //   updateAdminStatus(1);
    // }
  };

  ws.value.onmessage = (event) => {

    try {
      const data = JSON.parse(event.data);
      console.log('用户端来消息了',data);

      switch (data.type) {
        case 'message':
          // 收到新消息时更新会话列表
          if (data.data.sessionId === currentSessionId.value) {
            messages.value.push({
              ...data.data,
              senderType: data.data.senderType || 1,
              messageType: data.data.messageType || 1
            });
            scrollToBottom();
          } else {
            // 非当前会话的新消息，重新加载会话列表更新未读计数
            loadSessions();
          }
          break;
        case 'typing':
          if (data.sessionId === currentSessionId.value) {
            isUserTyping.value = data.status;
          }
          break;
        case 'session':
          // 会话状态变化时重新加载列表
          loadSessions();
          break;
        default:
          console.log('未知消息类型', data);
      }
    } catch (e) {
      console.error('解析WebSocket消息失败', e);
    }
  };

  ws.value.onclose = () => {
    console.log('WebSocket连接已关闭');
    // 连接关闭时更新状态为离线
    // if (adminStatus.value !== 0) {
    //   adminStatus.value = 0;
    //   updateAdminStatus(0);
    // }
    // 尝试重连
    setTimeout(initWebSocket, 3000);
  };

  ws.value.onerror = (error) => {
    console.error('WebSocket错误:', error);
  };
};

// 发送消息
const sendMessage = () => {
  const content = messageContent.value.trim();
  if (content && ws.value && ws.value.readyState === WebSocket.OPEN && currentSessionId.value) {
    const message = {
      sessionId: currentSessionId.value,
      senderId: adminId,
      content: content,
      messageType: 1, // 文字消息
      senderType: 2,  // 客服发送
      sendTime: new Date().toISOString()
    };

    ws.value.send(JSON.stringify({
      type: 'message',
      data: message
    }));

    messages.value.push(message);
    messageContent.value = '';
    scrollToBottom();
  }
};

// 处理输入状态
const handleTyping = () => {
  if (ws.value && ws.value.readyState === WebSocket.OPEN && currentSessionId.value) {
    // 发送正在输入状态
    ws.value.send(JSON.stringify({
      type: 'typing',
      sessionId: currentSessionId.value,
      status: true,
      role: 'admin'
    }));

    if (typingTimer.value) {
      clearTimeout(typingTimer.value);
    }

    // 3秒后发送停止输入状态
    typingTimer.value = setTimeout(() => {
      if (ws.value && ws.value.readyState === WebSocket.OPEN) {
        ws.value.send(JSON.stringify({
          type: 'typing',
          sessionId: currentSessionId.value,
          status: false,
          role: 'admin'
        }));
      }
    }, 3000);
  }
};

// 选择图片
const selectImage = () => {
  imageInput.value.click();
};

// 处理图片选择
const handleImageSelect = (e) => {
  const file = e.target.files[0];
  if (file && ws.value && ws.value.readyState === WebSocket.OPEN && currentSessionId.value) {
    const reader = new FileReader();
    reader.onload = (event) => {
      const base64Image = event.target.result;

      const message = {
        sessionId: currentSessionId.value,
        senderId: adminId,
        content: base64Image,
        messageType: 2, // 图片消息
        senderType: 2,  // 客服发送
        sendTime: new Date().toISOString()
      };

      ws.value.send(JSON.stringify({
        type: 'message',
        data: message
      }));

      messages.value.push(message);
      scrollToBottom();
    };
    reader.readAsDataURL(file);
    e.target.value = '';
  }
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messageContainer.value) {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
    }
  });
};

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return '';

  const date = new Date(timeString);
  const now = new Date();

  // 今天
  if (date.toDateString() === now.toDateString()) {
    return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  }

  // 昨天
  const yesterday = new Date(now);
  yesterday.setDate(now.getDate() - 1);
  if (date.toDateString() === yesterday.toDateString()) {
    return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  }

  // 今年
  if (date.getFullYear() === now.getFullYear()) {
    return `${date.getMonth() + 1}-${date.getDate()}`;
  }

  // 其他年份
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
};

// 监听搜索关键词变化
watch(searchKeyword, filterSessions);

// 页面加载时初始化
onMounted(() => {
  if (!adminId) {
    router.push('/admin/login');
    return;
  }

  // // 加载客服信息
  // const {$axios} = require('@/main').default.config.globalProperties;
  // $axios.get(`/admin/info/${adminId}`)
  //     .then(res => {
  //       if (res.data.code === 0 && res.data.data) {
  //         adminName.value = res.data.data.name || res.data.data.username;
  //         adminStatus.value = res.data.data.status || 1;
  //       }
  //     })
  //     .catch(err => {
  //       console.error('加载客服信息失败:', err);
  //     });

  loadSessions();
  initWebSocket();
});

// 页面卸载时清理
onUnmounted(() => {
  // 页面关闭时更新状态为离线
  updateAdminStatus(0);
  if (ws.value) {
    ws.value.close();
  }
  if (typingTimer.value) {
    clearTimeout(typingTimer.value);
  }
});
</script>

<style scoped>
.admin-dashboard {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f7;
  overflow: hidden;
}

.dashboard-header {
  background-color: #165DFF;
  color: white;
  padding: 0 20px;
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.dashboard-header h1 {
  margin: 0;
  font-size: 18px;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-info span {
  margin-right: 15px;
}

.logout-btn {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  padding: 5px 10px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.logout-btn:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.dashboard-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.session-list {
  width: 320px;
  background-color: white;
  border-right: 1px solid #e5e7eb;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.search-box {
  position: relative;
  padding: 12px;
  border-bottom: 1px solid #e5e7eb;
}

.search-box input {
  width: 100%;
  padding: 8px 12px 8px 36px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  font-size: 14px;
}

.search-box i {
  position: absolute;
  left: 20px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
}

.session-items {
  flex: 1;
  overflow-y: auto;
}

.session-item {
  padding: 12px 16px;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: background-color 0.2s;
  border-bottom: 1px solid #f5f5f5;
}

.session-item:hover {
  background-color: #f9fafb;
}

.session-item.active {
  background-color: #e8f3ff;
}

/* 未分配未读会话样式 */
.session-item.unassigned-unread {
  background-color: #fff8f8;
  border-left: 3px solid #ff4d4f;
}

.session-avatar {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  overflow: hidden;
  position: relative;
  flex-shrink: 0;
}

.session-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.unread-badge {
  position: absolute;
  top: -2px;
  right: -2px;
  background-color: #f53f3f;
  color: white;
  font-size: 12px;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 未分配会话标签 */
.unassigned-tag {
  position: absolute;
  top: 5px;
  right: 5px;
  background-color: #ff4d4f;
  color: white;
  font-size: 12px;
  padding: 1px 5px;
  border-radius: 3px;
}

.session-info {
  margin-left: 12px;
  flex: 1;
  min-width: 0;
}

.session-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.session-header h4 {
  margin: 0;
  font-size: 15px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.session-time {
  font-size: 12px;
  color: #999;
}

.last-message {
  margin: 0;
  font-size: 14px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #f9fafb;
  overflow: hidden;
}

.chat-header {
  padding: 12px 20px;
  background-color: white;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-header .user-info {
  display: flex;
  align-items: center;
}

.chat-header .user-info img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.chat-header .user-info div {
  margin-left: 12px;
}

.chat-header h3 {
  margin: 0 0 4px 0;
  font-size: 16px;
  color: #333;
}

.user-phone, .user-anonymous {
  margin: 0;
  font-size: 13px;
  color: #666;
}

.user-anonymous {
  color: #999;
}

.chat-tools {
  display: flex;
  gap: 8px;
}

.tool-btn {
  background-color: #f5f5f5;
  border: none;
  color: #666;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  transition: all 0.3s;
}

.tool-btn.active {
  background-color: #165DFF;
  color: white;
}

.tool-btn i {
  margin-right: 5px;
}

.tool-btn:hover:not(.active) {
  background-color: #e5e5e5;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.message-item {
  display: flex;
  align-items: flex-start;
  max-width: 70%;
}

.admin-message {
  align-self: flex-start;
}

.user-message {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.admin-message .avatar {
  margin-right: 10px;
}

.user-message .avatar {
  margin-left: 10px;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.message-content {
  padding: 10px 15px;
  border-radius: 18px;
  word-break: break-word;
  position: relative;
}

.admin-content {
  background-color: white;
  border: 1px solid #e5e5e5;
}

.user-content {
  background-color: #165DFF;
  color: white;
}

.message-time {
  font-size: 11px;
  margin-top: 5px;
  display: block;
  opacity: 0.7;
}

.message-image {
  max-width: 200px;
  max-height: 200px;
  border-radius: 8px;
  cursor: pointer;
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 8px 15px;
}

.dot {
  width: 8px;
  height: 8px;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 50%;
  animation: typing 1.4s infinite ease-in-out both;
}

.dot:nth-child(1) {
  animation-delay: -0.32s;
}

.dot:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

.input-area {
  padding: 15px;
  background-color: white;
  border-top: 1px solid #e5e7eb;
}

.input-tools {
  margin-bottom: 10px;
  display: flex;
  gap: 10px;
}

.hidden {
  display: none;
}

.input-wrapper {
  display: flex;
  gap: 10px;
}

.input-wrapper input {
  flex: 1;
  padding: 10px 15px;
  border: 1px solid #e5e5e5;
  border-radius: 20px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.3s;
}

.input-wrapper input:focus {
  border-color: #165DFF;
}

.send-btn {
  background-color: #165DFF;
  color: white;
  border: none;
  border-radius: 20px;
  padding: 0 20px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.send-btn:hover {
  background-color: #0E42D2;
}

.no-session {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
}

.no-session i {
  font-size: 48px;
  margin-bottom: 15px;
}
</style>
